package com.dream.cgomall.service.impl;

import com.dream.cgomall.dao.CgoGoodTrolletDao;
import com.dream.cgomall.dao.CgoGoodsDao;
import com.dream.cgomall.dto.GoodListID;
import com.dream.cgomall.dto.TroGoodDTO;
import com.dream.cgomall.dto.TrolletDTO;
import com.dream.cgomall.entity.CgoGoodTrollet;
import com.dream.cgomall.entity.CgoGoods;
import com.dream.cgomall.service.CgoGoodTrolletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
public class CgoGoodTrolletServiceImpl implements CgoGoodTrolletService{
    @Autowired
    private CgoGoodTrolletDao CGTD;
    @Autowired
    private CgoGoodsDao cgoGoodsDao;
    @Override
    public Boolean insertTro(TrolletDTO trolletDTO) {
       String Attr="";
        List<String> list=trolletDTO.getGoodAttr();
        for (String attr:list) {
            Attr+=","+attr;
        }
        Attr=Attr.substring(1);
        CgoGoodTrollet cgt=new CgoGoodTrollet(trolletDTO.getUserId(),trolletDTO.getGoodId(),Attr, trolletDTO.getGoodNum(),trolletDTO.getPrice(), LocalDateTime.now());
        List<CgoGoodTrollet> cgt1=CGTD.selectAll();
        for (CgoGoodTrollet cgtAll:cgt1) {
            if (cgt.getUserId()==cgtAll.getUserId() && cgt.getGoodId()==cgtAll.getGoodId() && cgt.getGoodAttr().equals(cgtAll.getGoodAttr())){
                int res=CGTD.updateId(cgtAll);
                return true;
            }
        }
        int result= CGTD.insertTro(cgt);
        if (result>0){
            return true;
        }
        return false;
    }

    @Override
    public List<TroGoodDTO> TroList(int userId) {
        List<TroGoodDTO> TGD=new ArrayList<>();
        List<CgoGoodTrollet> Tro=CGTD.selectA(userId);
        for (CgoGoodTrollet cgT:Tro) {
            CgoGoods CG=cgoGoodsDao.findGoods(cgT.getGoodId());
            TroGoodDTO Tld=new TroGoodDTO(cgT.getId(),CG.getGoodName(),cgT.getPrice(),CG.getPic(),cgT.getGoodAttr(), cgT.getGoodNum(),false);
            TGD.add(Tld);
        }
        return TGD;
    }

    @Override
    public double All(GoodListID goodListID) {
       double all=0;
        List<CgoGoodTrollet> Tro=null;
        for (int b:goodListID.getGoodsId()) {
            Tro=CGTD.selectMoneyAndNum(b);
            for (CgoGoodTrollet cgo:Tro) {
                all+=cgo.getGoodNum()*cgo.getPrice();
            }
        }
        System.out.println(all);
       return  all;
    }

    @Override
    public boolean deleteGoods(GoodListID goodListID) {
        List<Integer> idG=goodListID.getGoodsId();
        int result=0;
        for (int id:idG) {
           result+=CGTD.deleteGoods(id);
        }
       if (result>0){
           return  true;
       }
        return false;
    }
}
